package main

import (
	"fmt"
	"net"
	"sync"
	"io"
	"time"
)

type Server struct {
	Ip string
	Port int

	// 在线用户的列表
	OnlineMap map[string] *User
	mapLock sync.RWMutex

	//消息广播的 channel
	Message chan string
}

func NewServer(ip string, port int) *Server {
	server := &Server {
		Ip : ip,
		Port : port,
		OnlineMap: make(map[string]*User),
		Message: make(chan string),
	}

	return server
}


func (this *Server) ListenMessager() {
	for {
		msg := <- this.Message
		this.mapLock.Lock()
		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.mapLock.Unlock()
	}
}


func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[ " + user.Addr + " ]" + user.Name + " : " + msg
	
	this.Message <- sendMsg
}


func (this *Server) Handler(conn net.Conn) {
	fmt.Println("链接建立成功")

	user := NewUser(conn, this)

	user.Online()

	isLive := make(chan bool)
/*
	// 用户上线
	this.mapLock.Lock()
	this.OnlineMap[user.Name] = user
	this.mapLock.Unlock()
*/

	// 广播当前用户上线消息

	//this.BroadCast(user, "已上线")


	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				//this.BroadCast(user, "下线")
				user.Offline()
				return
			}

			if err != nil && err != io.EOF {
				fmt.Println("Conn Read err: ", err)
				return
			}

			// 提取用户的消息(去掉'\n')

			msg := string(buf[:n-1])
			//this.BroadCast(user, msg)
			user.DoMessage(msg)

			isLive <- true
		}
	}()
	
	for {
		select {
		case <- isLive:
		case <- time.After(time.Minute* 10):
			user.SendMsg("你被踢了\n")
			close(user.C)
			conn.Close()
			return
		}
	}
}


func (this *Server) Start() {
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net.Listen err: ", err)
		return
	}

	defer listener.Close()

	go this.ListenMessager()

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener accept err: ", err)
			continue
		}
		
		//do Handler
		go this.Handler(conn)
	}
}

func main() {
	server := NewServer("127.0.0.1", 8888)
	server.Start()
}
